// 第七步：编写服务器运算形式
#pragma once
#include <iostream>
#include "Protocol.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};

class ServerCal
{
public:
    ServerCal()
    {
    }
    ~ServerCal()
    {
    }

public:
    Response CalculatorHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp.result = req.left_d + req.right_d;
            break;
        case '-':
            resp.result = req.left_d - req.right_d;
            break;
        case '*':
            resp.result = req.left_d * req.right_d;
            break;
        case '/':
            {
                if(req.right_d == 0)
                    resp.code = Div_Zero;
                else
                    resp.result = req.left_d / req.right_d;
            }
            break;
        case '%':
            {
                if(req.right_d == 0)
                    resp.code = Mod_Zero;
                else
                    resp.result = req.left_d % req.right_d;
            }
            break;
        default:
            resp.code = Other_Oper;
            break;
        }
        return resp;
    }

    std::string Calculator(std::string &package)
    {
        // "len"\n"100 + 200"\n
        std::string content;
        bool r = Decode(package, &content); // "len"\n"10 + 20"\n
        if(!r)  return "";
        
        // "10 + 20"
        Request req;
        r = req.Deserialize(content);   // req(left_d:10, op:+, right_d:20)
        if(!r)  return "";
        
        content = "";
        Response resp = CalculatorHelper(req);  // resp(result:30, code:0)
        
        resp.Serialize(&content);   // "30 0"
        content = Encode(content);  // "len"\n"30 0"\n  // 加密（网络）

        return content;
    }
};
